#include "client_Hpp.hpp"

#include <sys/unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <string>
#include <chrono>
#include <thread>
#include <unistd.h>
#include <iostream>

#include <CoreGraphics/CoreGraphics.h>
// #include<>
// using namespace std;

uint8_t *screen(int &w, int &h)
{
    CGImageRef img = CGWindowListCreateImage(
        CGRectMake(10, 70, 5, 5),
        kCGWindowListOptionOnScreenOnly,
        kCGNullWindowID,
        kCGWindowImageDefault);

    w = (int)CGImageGetWidth(img);
    h = (int)CGImageGetHeight(img);

    //拿到原始像素
    CGDataProviderRef provider = CGImageGetDataProvider(img);
    CFDataRef imageData = CGDataProviderCopyData(provider);
    uint8_t *bytes = (uint8_t *)CFDataGetBytePtr(imageData);

    return bytes;
}

void client()
{
    //client 和 server代码几乎一样,有一些细微差别
    int socketFd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in serverAddress; //服务端地址
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = 0x00000000;
    serverAddress.sin_port = 0x10FF;

    std::cout << "wait for connct to server" << std::endl;
    //客户端直接链接服务器,无须其他设置
    connect(socketFd, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
    std::cout << "connected server ok" << std::endl;

    while (true)
    {
        sleep(1);
        std::cout<<"here"<<std::endl;
        std::string data = "zhangyue hello socket";
        //截图并发送
        int w;
        int h;
        uint8_t *pixels = screen(w, h);
        std::cout << "sleep and send "
                  << "(" << pixels << ")" << std::endl;
        // send(socketFd, data.c_str(), sizeof(data), 0); //因为string是个对象,所以不能直接发送,要c_str()
        send(socketFd, pixels, w * h * 4, 0);
    }
}

int main(int argc, char **argv)
{
    client();
    return 0;
}